package com.freecloud.framework.config;

import com.freecloud.framework.interceptor.ClientTokenInterceptor;
import com.freecloud.framework.plugin.feign.FeignDecoder;
import feign.Feign;
import feign.Logger;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import okhttp3.ConnectionPool;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@AutoConfigureBefore(FeignAutoConfiguration.class)
@Configuration
@ConditionalOnClass(Feign.class)
public class FeignConfig {


	private int feignOkHttpReadTimeout = 60;
	private int feignConnectTimeout = 60;
	private int feignWriteTimeout = 120;

	/**
	 * 请求客户端方式
	 * @return
	 */
	@Bean
	public okhttp3.OkHttpClient okHttpClient() {
		return new okhttp3.OkHttpClient.Builder()
				.readTimeout(feignOkHttpReadTimeout, TimeUnit.SECONDS)
				.connectTimeout(feignConnectTimeout, TimeUnit.SECONDS)
				.writeTimeout(feignWriteTimeout, TimeUnit.SECONDS).connectionPool(new ConnectionPool())
				.build();
	}

	/**
	 * 编码方式
	 * @return
	 */
	@Bean
	public GsonEncoder getGsonEncoder(){
		return new GsonEncoder();
	}

	/**
	 * 解码
	 * @return
	 */
	@Bean
	public FeignDecoder getFeignDecoder(){
		return new FeignDecoder();
	}

	/**
	 * feign日志级别
	 * @return
	 */
	@Bean
	Logger.Level feignLevel() {
		return Logger.Level.FULL;
	}

	/**
	 * 业务服务端调用拦截器，增加token
	 * @return
	 */
	@Bean
	ClientTokenInterceptor getClientTokenInterceptor(){
		return new ClientTokenInterceptor();
	}
}
